package com.miyu.system.utils.webService;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import javax.wsdl.Output;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.List;

public class webServiceXml {
    public static void main(String[] args) throws Exception {

        String namespace="http://webService.utils.system.miyu.com/";
        String postUrl="http://localhost:18767/webService/testWebService/sendMsg?wsdl";
        String method="sendMsg";
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        root.addElement("serverName").addText("getFinancialDebit");
        root.addElement("format").addText("format");
        root.addElement("callOperator").addText("callOperator");
        root.addElement("certificate").addText("certificate");
        document.asXML();


        //自定义soap报文模板 注意：xmlns:web 与<soapenv:Body>后的属性（web）要一致
        StringBuffer sb=new StringBuffer("");
        sb.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"").append(namespace).append("\">");
        sb.append("<soapenv:Header/>");
        sb.append("<soapenv:Body>");
        sb.append(method);
        sb.append(">");
        sb.append("<web:"+method+">");

        sb.append("<msgHeader>");
        sb.append("<![CDATA[");
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<serverName>getFinancialDebit</serverName>");
        sb.append("<format>format</format>");
        sb.append("<callOperator>callOperator</callOperator>");
        sb.append("<certificate>certificate</certificate>");
        sb.append("</root>");
        sb.append("]]>");
        sb.append("</msgHeader>");
        sb.append("<msgBody>");
        sb.append("<![CDATA[");
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<root>");
        sb.append("<serverName>getFinancialDebit</serverName>");
        sb.append("<format>format</format>");
        sb.append("<callOperator>callOperator</callOperator>");
        sb.append("<certificate>certificate</certificate>");
        sb.append("</root>");
        sb.append("]]>");
        sb.append("</msgBody>");
        sb.append("</web:"+method+">");
        sb.append("></soapenv:Body></soapenv:Envelope>");


        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        httpPost.setConfig(requestConfig);

        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", "");
            StringEntity data = new StringEntity(sb.toString(), Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            Output output = null;
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
                /* //转义操作*/
                String xml = StringEscapeUtils.unescapeXml(retStr);
//                StringEscapeUtils.unescapeXml(retStr);
                xml = xml.substring(xml.indexOf("<msgHeader>")+"<msgHeader>".length(),xml.indexOf("</msgHeader>"));
                System.out.println(xml);
                Document documenta = new SAXReader().read(new StringReader(xml));
                Element roots = documenta.getRootElement();
                List<Element> childElements = roots.elements();
                for (int i = 0; i <childElements.size(); i++) {
                    Element element = childElements.get(i);
                    System.out.println(element.getName()+"="+element.getText());

                }
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
        }

    }

    /**
     * xml解析
     * @param xml
     * @param repli
     * @return
     */
    public static JSONObject jxXml (String xml,String repli) {
        JSONObject rs = new JSONObject();
        String b = "<"+repli+">";
        String end = "</"+repli+">";
        xml = xml.substring(xml.indexOf(b)+b.length(),xml.indexOf(end));
        Document document=null;
        try {
            document = new SAXReader().read(new StringReader(xml));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //	根
        Element root = document.getRootElement();
        rs = cteXml(root,rs);
        return rs;

    }

    /**
     * 递归解析xml 取末级节点
     * @param root
     * @param rs
     * @return
     */
    public static JSONObject cteXml(Element root,JSONObject rs) {
        List<Element> list = root.elements();
        if(list.size()==0) {
            rs.put(root.getName(), root.getTextTrim());
        }else {
            for (Element element:list) {
                rs = cteXml(element,rs);
            }
        }
        return rs;

    }
}
